package goodbaby.dklt.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

public abstract class CommonAdapter<T> extends BaseAdapter  
{  
    protected final int mItemLayoutId;
    protected LayoutInflater mInflater;
    protected Context mContext;
    protected List<T> mDatas;
  
    public CommonAdapter(Context context,int itemLayoutId,List<T> mDatas)  
    {  
        this.mContext = context;  
        this.mInflater = LayoutInflater.from(mContext);  
        this.mDatas = mDatas;  
        this.mItemLayoutId = itemLayoutId;  
    }  
  
    @Override  
    public int getCount()  
    {  
    	if(mDatas == null){
    		return 0;
    	}
        return mDatas.size();  
    }  
    
    public void setData(List<T> datas){
    	mDatas = datas;
    	notifyDataSetChanged();
    }
    
    public void addData(T data){
    	if(mDatas == null){
    		mDatas = new ArrayList<T>();
    	}
    	mDatas.add(data);
    	notifyDataSetChanged();
    }

    public void removeData(T data){
        if(mDatas == null || mDatas.size()==0){
            return;
        }
        try {
            mDatas.remove(data);
            notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void addData(List<T> datas){
    	if(mDatas == null){
    		mDatas = new ArrayList<T>();
    	}
    	mDatas.addAll(datas);
    	notifyDataSetChanged();
    }
  
    @Override  
    public T getItem(int position)  
    {  
        return mDatas.get(position);  
    }  
  
    @Override  
    public long getItemId(int position)  
    {  
        return position;  
    }  
  
    @Override  
    public View getView(int position, View convertView, ViewGroup parent)  
    {  
        final ViewHolder viewHolder = getViewHolder(position, convertView,  
                parent);  
        convert(viewHolder, getItem(position),position);  
        return viewHolder.getConvertView();  
  
    }  
  
    public abstract void convert(ViewHolder helper, T item,int position);  
  
    private ViewHolder getViewHolder(int position, View convertView,  
            ViewGroup parent)  
    {  
        return ViewHolder.get(mContext, convertView, parent, mItemLayoutId,  
                position);  
    }  
  
}  
